package common

import (
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"itluv.me/ginessential/model"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	// 链接数据库 参照gorm文档 https://gorm.io/zh_CN/docs/connecting_to_the_database.html
	//dsn := "root:twitm.123@tcp(127.0.0.1:3306)/ginessential?charset=utf8mb4&parseTime=True&loc=Local"

	// 从yml文件读取数据库配置
	dsn := viper.GetString("datasource.username") +
		":" +
		viper.GetString("datasource.password") +
		"@tcp(" +
		viper.GetString("datasource.host") +
		":" +
		viper.GetString("datasource.port") +
		")/" +
		viper.GetString("datasource.database") +
		"?charset=" +
		viper.GetString("datasource.charset") +
		"&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("faild to connect database, rtt: " + err.Error())
	}
	// gorm创建数据表
	errs := db.AutoMigrate(&model.User{})
	if errs != nil {
		panic("gorm创建数据表失败" + err.Error())
	}
	DB = db
	return db
}

func GetDB() *gorm.DB {
	return DB
}
